package com.shyroke.daydayzhuansvc.service.impl;

import cn.hutool.core.util.StrUtil;
import com.querydsl.core.QueryResults;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.shyroke.daydayzhuanapi.constant.RedisKeyPrefix;
import com.shyroke.daydayzhuanapi.dto.AdvertDto;
import com.shyroke.daydayzhuanapi.dto.AdvertRequest;
import com.shyroke.daydayzhuanapi.entity.AdvertEntity;
import com.shyroke.daydayzhuanapi.entity.QAdvertEntity;
import com.shyroke.daydayzhuandao.respository.AdvertRepository;
import com.shyroke.daydayzhuansvc.service.IAdvertService;
import com.shyroke.daydayzhuansvc.service.IOSSService;
import com.shyroke.daydayzhuansvc.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 类名 ：
 * 用法 ：
 * 创建人 ： shyroke
 * 时间：2019/1/14 10:31
 */
@Service
public class AdvertService implements IAdvertService {
    @Autowired
    private IOSSService ossSerivce;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AdvertRepository advertRepository;
    @Autowired
    private JPAQueryFactory queryFactory;
    @Autowired
    private com.shyroke.daydayzhuanapi.mapper.AdvertMapper advert2Mapper;

    @Override
    public TabelData<AdvertDto> getAdvertList(Page page, AdvertRequest request) {

        TabelData tabelData = new TabelData();
        QAdvertEntity qAdvertEntity = QAdvertEntity.advertEntity;
        JPAQuery<AdvertEntity> query = queryFactory.selectFrom(qAdvertEntity);

        if(StrUtil.isNotBlank(request.getUsed())){
            query = query.where(qAdvertEntity.used.eq(request.getUsed()));
        }

        QueryResults<AdvertEntity> queryResults = query
                .offset(PageRequest.of(page.getPage() - 1, page.getLimit()).getOffset()).limit(page.getLimit())
                .orderBy(qAdvertEntity.id.desc())
                .fetchResults();

        List<AdvertDto> list = queryResults.getResults().stream().map(e -> {
            AdvertDto advertDto = advert2Mapper.entityToDto(e);
            if(!StringUtils.isEmpty(advertDto.getUrl())){
                advertDto.setUrl(ossSerivce.getImgUrl(advertDto.getUrl()));
            }
            return advertDto;
        }).collect(Collectors.toList());


        tabelData.setCount((int)queryResults.getTotal());
        tabelData.setData(list);

        return tabelData;
    }

    /**
     * 1、 删除库里的记录
     * 2、先删除OSS上的图片
     * @param id
     */
    @Override
    @Transactional
    public void deleteById(Integer id) {
        Optional<AdvertEntity> optionalAdvertEntity = advertRepository.findById(id);
        if(optionalAdvertEntity.isPresent()){
            AdvertEntity advertEntity = optionalAdvertEntity.get();
            //1、 删除库里的记录
            advertRepository.deleteById(id);
            //2、先删除OSS上的图片
            ossSerivce.deleteImg(OSSClientConstants.BUCKET_NAME,advertEntity.getUrl());
            //删除缓存
            redisTemplate.delete(RedisKeyPrefix.ADVERTLIST);
        }
    }

    @Override
    public AdvertDto getAdvertById(Integer id) {
        Optional<AdvertEntity> optionalAdvertEntity = advertRepository.findById(id);
        if(!optionalAdvertEntity.isPresent()){
            return null;
        }
        AdvertEntity advertEntity = optionalAdvertEntity.get();
        AdvertDto advertDto = advert2Mapper.entityToDto(advertEntity);
        advertDto.setUrl(ossSerivce.getImgUrl(advertDto.getUrl()));
        return advertDto;
    }

    @Override
    public void update(AdvertDto advertdto) {
        Optional<AdvertEntity> optionalAdvertEntity = advertRepository.findById(advertdto.getId());
        if(optionalAdvertEntity.isPresent()){
            AdvertEntity advertEntity = optionalAdvertEntity.get();
            if(StrUtil.isNotBlank(advertdto.getUrl())){
                advertEntity.setUrl(CommonUtil.deleteOSSImgPre(advertdto.getUrl()));
            }
            advertEntity.setUsed(advertdto.getUsed());
            advertEntity.setEndTime(advertdto.getEndTime());
            advertEntity.setLink(advertdto.getLink());
            advertEntity.setDesc(advertdto.getDesc());
            advertRepository.save(advertEntity);
        }
        //删除缓存
        redisTemplate.delete(RedisKeyPrefix.ADVERTLIST);
    }

    @Override
    public void save(AdvertDto advertdto) {
        AdvertEntity advertEntity = advert2Mapper.dtoToEntity(advertdto);
        advertRepository.save(advertEntity);
        //删除缓存
        redisTemplate.delete(RedisKeyPrefix.ADVERTLIST);
    }

    @Override
    public List<AdvertDto> getList() {
        //判断缓存中是否存在，如果存在则返回，否则返回null
        List<AdvertDto> advertList = RedisUtils.readList(RedisKeyPrefix.ADVERTLIST);

        if(CollectionUtils.isEmpty(advertList)){
            List<AdvertEntity> advertEntityList = advertRepository.findByUsed("1");
            List<AdvertDto> list = advertEntityList.stream().map(e -> advert2Mapper.entityToDto(e)).collect(Collectors.toList());
            //插入缓存
            redisTemplate.opsForValue().set(RedisKeyPrefix.ADVERTLIST,list);
        }
        return advertList;
    }
}
